import React, { Component } from 'react'
import { Card, Form, Input, Button, Checkbox, message } from 'antd'
import Logo from 'assets/logo.png'
import styles from './index.module.scss'
import { login } from 'api/login'
import { setToken } from 'utils/storage'

export default class Login extends Component {
  state = {
    loading: false,
  }
  formFinish = async ({ mobile, code }) => {
    this.setState(() => {
      return {
        loading: true,
      }
    })
    try {
      const { data } = await login(mobile, code)
      setToken(data.token)
      // console.log(this.props)
      const { state } = this.props.location
      if (state) {
        this.props.history.push(state.from)
      } else {
        this.props.history.push('/home')
      }
      message.success('登录成功')
    } catch (err) {
      console.dir(err)
      message.error(err.response?.data.message, 1, () => {
        this.setState({
          loading: false,
        })
      })
    }
  }
  render() {
    return (
      <div className={styles.login}>
        <Card className="login-container">
          <img src={Logo} alt="" className="login-logo" />
          <Form
            size="large"
            validateTrigger={['onBlur', 'onChange']}
            onFinish={this.formFinish}
          >
            <Form.Item
              name="mobile"
              rules={[
                { required: true, message: '请输入手机号' },
                {
                  pattern: /^1[3|5|7|8]\d{9}$/,
                  message: '手机号格式错误',
                },
              ]}
            >
              <Input placeholder="请输入手机号" />
            </Form.Item>

            <Form.Item
              name="code"
              rules={[
                { required: true, message: '请输入验证码' },
                {
                  pattern: /^\d{6}$/,
                  message: '验证码格式不对',
                },
              ]}
            >
              <Input placeholder="请输入验证码" />
            </Form.Item>

            <Form.Item
              valuePropName="checked"
              name="remember"
              rules={[
                {
                  validator: (_, value) => {
                    if (value) {
                      return Promise.resolve()
                    } else {
                      return Promise.reject(
                        new Error('请勾选用户协议和隐私条款')
                      )
                    }
                  },
                },
              ]}
            >
              <Checkbox>我已阅读并同意[用户协议]和[隐私条款]</Checkbox>
            </Form.Item>

            <Form.Item>
              <Button
                type="primary"
                htmlType="submit"
                block
                loading={this.state.loading}
              >
                登录
              </Button>
            </Form.Item>
          </Form>
        </Card>
      </div>
    )
  }
}
